<script setup lang="ts">
import type { FileItem, FormInstance, RequestOption } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { useForm } from '@/hooks'
import * as Regexp from '@/utils/regexp'
import { ConfigApi } from '@/apis'
import { useAppStore } from '@/stores'
import { fileToBase64 } from '@/utils/common'

const category = 'website'
const loading = ref(false)
const readonly = ref(true)
const config = ref()
const formRef = ref<FormInstance>()

const { form } = useForm({
  'website.logo': '',
  'website.title': '',
  'website.copyright': '',
  'website.icp': '',
})

const rules: FormInstance['rules'] = {
  'website.title': [{ required: true, match: Regexp.Name, message: '名称只能含有中文、数字、英文、下划线、短横线，长度为2-32位' }],
}

// logo
const logoFile = ref<FileItem>({ uid: 'logo' })
const onLogoUpload = (options: RequestOption) => {
  const controller = new AbortController()
  ;(async () => {
    const { onProgress, onError, onSuccess, fileItem } = options
    onProgress(20)
    if (!fileItem.file) {
      return
    }
    // 不能超过100kb
    if (fileItem.file.size > 1024 * 100) {
      Message.error('上传失败, 图片不能超过100KB')
      throw new Error('上传失败, 图片不能超过100KB')
    }

    fileToBase64(fileItem.file).then((res) => {
      form['website.logo'] = res
      onSuccess()
      Message.success('上传成功')
    }).catch((error) => {
      onError(error)
    })
  })()
  return {
    abort() {
      controller.abort()
    },
  }
}

const onLogoChange = (_: any, currentFile: any) => {
  logoFile.value = {
    ...currentFile,
  }
}

// 编辑
const onEdit = () => {
  readonly.value = false
}

// 重置
const reset = () => {
  formRef.value?.resetFields()
  for (const key in form) {
    form[key] = config.value?.[key]
  }
  logoFile.value.url = form['website.logo']
}

// 取消
const onCancel = () => {
  reset()
  readonly.value = true
}

// 保存
const onSave = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) {
    return false
  }

  await ConfigApi.updateConfigMap(form)
  Message.success('修改成功')
  useAppStore().initWebsiteConfig()
  readonly.value = true
}

// 查询详情
const getConfig = async () => {
  loading.value = true
  ConfigApi.listMapByCategory(category).then((res) => {
    config.value = res
    reset()
  }).finally(() => {
    loading.value = false
  })
}

onMounted(async () => {
  getConfig()
})
</script>

<template>
  <a-card :loading title="网站信息" class="section">
    <a-form ref="formRef" layout="vertical" :model="form" :rules :readonly :style="{ width: '500px' }">
      <a-form-item label="网站图标" field="'website.logo'" extra="网站logo图片, 大小不能超过100KB" :span="24">
        <a-upload
          :file-list="logoFile ? [logoFile] : []"
          accept="image/*"
          :show-file-list="false"
          :custom-request="onLogoUpload"
          :disabled="readonly"
          @change="onLogoChange"
        >
          <template #upload-button>
            <div :class="`arco-upload-list-item${logoFile?.status === 'error' ? ' arco-upload-list-item-error' : ''}`">
              <div v-if="logoFile?.url" class="arco-upload-list-picture custom-upload-avatar logo">
                <img :src="logoFile.url" alt="Logo">
                <div v-if="!readonly" class="arco-upload-list-picture-mask logo">
                  <icon-edit />
                </div>
              </div>
              <div v-else class="arco-upload-picture-card logo">
                <div class="arco-upload-picture-card-text">
                  <icon-upload />
                </div>
              </div>
            </div>
          </template>
        </a-upload>
      </a-form-item>
      <readonly-form-item label="网站名称" field="'website.title'" :span="24">
        <a-input v-model.trim="form['website.title']" placeholder="请输入网站名称" :max-length="32" show-word-limit />
      </readonly-form-item>
      <readonly-form-item label="网站版权信息" field="'website.copyright'" :span="24">
        <a-input v-model.trim="form['website.copyright']" placeholder="请输入网站版权信息" />
      </readonly-form-item>
      <readonly-form-item label="网站icp备案号" field="'website.icp'" :span="24">
        <a-input v-model.trim="form['website.icp']" placeholder="请输入网站icp备案号" />
      </readonly-form-item>
    </a-form>
    <template #extra>
      <ReadonlyEditButton
        :readonly="readonly"
        :deleteable="false"
        @edit="onEdit"
        @cancel="onCancel"
        @save="onSave"
      >
        <!-- <template #extra>
          <a-button class="btn" type="text" size="small">
            <template #icon>
              <icon-record />
            </template>
            恢复默认
          </a-button>
        </template> -->
      </ReadonlyEditButton>
    </template>
  </a-card>
</template>

<style lang="less" scoped>
.logo {
  width: 50px;
  height: 50px;
  min-width: 50px;
  line-height: 50px;
}
</style>
